package com.delong.spring.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

@Component
public class LoginFilter implements Filter {
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		HttpSession session = request.getSession(false);
		if (request.getServletPath().indexOf("login") != -1 || request.getServletPath().indexOf("css") != -1
				|| request.getServletPath().indexOf("auth") != -1 || request.getServletPath().indexOf("fav") != -1
				|| request.getServletPath().indexOf("js") != -1

		|| session != null && !session.isNew()) {
			// record the operation logs from user;
			System.out.println("--" + request.getServletPath());
			chain.doFilter(req, res);
		} else {
			if (request.getServletPath().indexOf("list") != -1) {
				response.sendRedirect("/user/login");
			} else {

				System.out.println("**" + request.getServletPath());
				response.getWriter().write("{code:'2'}");
			}
		}
		// chain.doFilter(req, res);
	}

	public void init(FilterConfig filterConfig) {
	}

	public void destroy() {
	}

}